package com.ashermed.cxzkxc;

import java.util.List;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ashermed.cxzkxc.R;
import com.ashermed.cxzkxc.bean.DataBean;
import com.ashermed.cxzkxc.util.Blutooth_Until;

/**
 * 数据同步中
 * @author jiang
 *
 */
public class Blutooth_Second extends Activity {

	String mDeviceName;
	String mDeviceAddress;
	TextView tv_number1, tv_number2, tv_data_complete,tv_data_loading1;
	Button btn_back;
	ProgressBar blu_pb;
    View view_close_blu_detailed;
	private String myBluetoothDeviceAddress; // ble 蓝牙地址
	private BluetoothManager myBluetoothManager;
	private BluetoothAdapter myBluetoothAdapter;
	private BluetoothGatt myBluetoothGatt;
	private Handler myHandler;
	private static final UUID uuid = UUID
			.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
	private static final UUID UUID_READ = UUID
			.fromString("0000ff0a-0000-1000-8000-00805f9b34fb");
	private static final UUID UUID_WRITE = UUID
			.fromString("0000ff0b-0000-1000-8000-00805f9b34fb");
	private BluetoothGattService myGattService;

	private BluetoothGattCharacteristic readGattCharacteristic;
	private BluetoothGattCharacteristic writeGattCharacteristic;
	private byte[] data; // 读取到的数值ֵ
	private String strData;
	private StringBuffer sbValues;

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case 1:
				tv_data_complete.setText("同步完成！！！");
				break;

			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.blutooth_activity_second);
		final Intent intent = getIntent();
		mDeviceName = intent.getStringExtra("EXTRAS_DEVICE_NAME");
		mDeviceAddress = intent.getStringExtra("EXTRAS_DEVICE_ADDRESS");

		init();
		
		btn_back.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(Blutooth_Second.this,CaseHistoryThreeInfoActivity.class);
				BaseActivity.flag="1";
				BaseActivity.boolIsLoadData=true;
				i.putExtra("toKindActivity", "C");
				Blutooth_Second.this.finish();
				startActivity(i);
				
			}
		});

	}
	
	
	
	
	@Override
	protected void onDestroy() {
		myBluetoothGatt = null;
		// TODO Auto-generated method stub
		super.onDestroy();
	}




	public void init(){
		
//		tv_number1 = (TextView) findViewById(R.id.tv_number1);
//		tv_number2 = (TextView) findViewById(R.id.tv_number2);
		tv_data_complete = (TextView) findViewById(R.id.tv_data_complete);
		tv_data_complete.setVisibility(View.GONE);
		view_close_blu_detailed = findViewById(R.id.view_close_blu_detailed);
		view_close_blu_detailed.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Blutooth_Second.this,CaseHistoryThreeInfoActivity.class);
				BaseActivity.flag="1";
				BaseActivity.boolIsLoadData=true;
				i.putExtra("toKindActivity", "C");
				Blutooth_Second.this.finish();
				startActivity(i);
				// TODO Auto-generated method stub
				
			}
		});
		tv_data_loading1 =  (TextView) findViewById(R.id.tv_data_loading1);
		blu_pb = (ProgressBar) findViewById(R.id.blu_pb);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_back.setVisibility(View.GONE);
//		tv_number1.setText(mDeviceName);
//		tv_number2.setText(mDeviceAddress);
		myHandler = new Handler();
		myBluetoothDeviceAddress = mDeviceAddress;
		myBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
		myBluetoothAdapter = myBluetoothManager.getAdapter();
		sbValues = new StringBuffer();
		connect(myBluetoothDeviceAddress);
		
	}

	public boolean connect(String paramString) { // paramString == ble mac
		if ((myBluetoothAdapter == null) || (paramString == null))
			return false;
		if ((myBluetoothDeviceAddress != null)
				&& (paramString.equals(myBluetoothDeviceAddress))
				&& (myBluetoothGatt != null)) {
			if (myBluetoothGatt.connect()) {
				System.out.println("mBluetoothGatt��Ϊ��");
				return true;
			}
			return false;
		}
		// 得到该蓝牙MAc的设备
		BluetoothDevice localBluetoothDevice = myBluetoothAdapter
				.getRemoteDevice(paramString);
		if (localBluetoothDevice == null)
			return false;
		// 连接Gatt ，回调，返回BluetoothGatt
		myBluetoothGatt = localBluetoothDevice.connectGatt(this, true,myGattCallback);
		myBluetoothDeviceAddress = paramString;
		return true;
	}

	private BluetoothGattCallback myGattCallback = new BluetoothGattCallback() {

		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status,
				int newState) {
			// TODO Auto-generated method stub
			super.onConnectionStateChange(gatt, status, newState);

			// 连接完成
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				System.err.println("连接上GATT！");
				myBluetoothGatt.getServices();
				// discover发现
				myBluetoothGatt.discoverServices();
				sbValues.insert(0, "connected...\n");
				myHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						// textViewValues.setText(sbValues);
						
						Log.i("jsc", "连接上GATT！");
						//tv_number2.setText("连接上GATT！");

					}
				});
				// 状态断开
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				System.out.println("连接断开！");

				sbValues.insert(0, "disconnected...\n");
				myHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						// textViewValues.setText(sbValues);
						//tv_number2.setText(sbValues);
						//Toast.makeText(Blutooth_Second.this, "连接断开！", 1).show();
						Log.i("jsc", "断开:" + sbValues);
					}
				});
			}
		}

		// 搜索蓝牙Mac 根据默认的UUID连接 去得到我们需要的UUID
		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			// TODO Auto-generated method stub
			super.onServicesDiscovered(gatt, status);
			if (myBluetoothGatt != null) {
				myGattService = myBluetoothGatt.getService(uuid);
			}

			if (myGattService != null) {
				String aaa = myGattService.getUuid().toString();
				Log.i("jsc", "获得BLE GATT Services 成功 : " + aaa);
				readGattCharacteristic = myGattService
						.getCharacteristic(UUID_READ);

				writeGattCharacteristic = myGattService
						.getCharacteristic(UUID_WRITE);
                myHandler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Toast.makeText(Blutooth_Second.this, "设备已连接", 1).show();
						
					}
				});
				// TODO Auto-generated method stub
				writeStringToGatt("5501");

			}

			// if (readGattCharacteristic != null
			// && writeGattCharacteristic != null) {
			// System.out.println("�ҵ���READ��WRITE");
			//
			// // mBluetoothGatt.setCharacteristicNotification(
			// // mGattCharacteristicWrite, true);
			// setCharacteristicNotification(readGattCharacteristic, true);
			//
			// boolean test = myBluetoothGatt
			// .readCharacteristic(readGattCharacteristic);
			// System.out.println("READ״̬ �� " + test);
			// }

		}

		private void writeStringToGatt(String dataString) {
			Log.i("jsc", "dataString:" + dataString);
			if (dataString != null){
				byte[] data = getBytesByString(dataString);
				writeGattCharacteristic.setValue(data);
				myBluetoothGatt.writeCharacteristic(writeGattCharacteristic);
			}else {
				return;
			}
		}

		public int pack_iteration = 1; // 包数量迭代
		int select_pack_number2;

		@Override
		public void onCharacteristicRead(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic, int status) {
			// if(cc<3){
			// cc++;
			// writeStringToGatt("55020"+ 1 + "00"); // 55020000
			//
			// }
			// TODO Auto-generated method stub
			super.onCharacteristicRead(gatt, characteristic, status);
			data = characteristic.getValue();
			// 查看接收到的值ֵ
			// System.out.println("Read_收到的数据是 ：" + data.toString());
			if (data != null && data.length > 0) {
				strData = getStringByBytes(data) + "\n";
				System.out.println("Read_收到的数据是 ： " + strData); // DDF86296560301EA000000000000000000000000
				Log.i("jsc", "Read_收到的数据是 ： " + strData);

				sbValues.insert(0, strData);
				// myHandler.post(new Runnable() {
				//
				// @Override
				// public void run() { }
				// });
				try {

					String select_Str = strData.substring(0, 2);
					if (select_Str.equals("AA")) { // 为数据？
													// AA010002 AA03
						String select_AA = strData.substring(2, 4);
						//Log.i("jsc", "select_AA:" + select_AA);
						if (select_AA.equals("01")) { // 判断是获取包数 还是 删除完成
							String select_pack_number = strData.substring(6, 8); // 只有两位
																					// 03
							//Log.i("jsc", "select_pack_number:"+ select_pack_number);
							int select_pack_number_int = Integer.valueOf(select_pack_number);

							if (select_pack_number_int > 0) {
								select_pack_number2 = select_pack_number_int;
								writeStringToGatt("55020" + pack_iteration
										+ "00"); // 55020000
								pack_iteration++;
								// for (int i = 1; i <3 ; i++) {
								// //select_pack_number_int + 1
								//
								// String select_pack_send_number =
								// String.format("%02d", i);
								// writeStringToGatt("5502"+
								// select_pack_send_number + "00"); // 55020000
								// }
								// writeStringToGatt("5502"+ 1 + "00"); //
								// 55020000
							} else {
								myHandler.post(new Runnable() {

									@Override
									public void run() {
										Toast.makeText(Blutooth_Second.this,"包的数量为零", 1).show();
										blu_pb.setVisibility(View.GONE);
										tv_data_complete.setVisibility(View.VISIBLE);
										btn_back.setVisibility(View.VISIBLE);
										tv_data_complete.setText("同步数据已完成！");
										tv_data_loading1.setText("已同步"+Blutooth_Until.blutooth_lists.size()+"条数据!");
										Blutooth_Until.blutooth_lists.clear();
										//Blutooth_Second.this.finish();
									}
								});
								Log.i("jsc", "包的数量为零");
								return;
							}
						} else if (select_AA.equals("03")) {
							// Toast.makeText(Blutooth_Second.this, "删除完毕",
							// 1).show();
							Log.i("jsc", "删除完毕");
							myHandler.post(new Runnable() {

								@Override
								public void run() {
									blu_pb.setVisibility(View.GONE);
									tv_data_complete.setVisibility(View.VISIBLE);
									btn_back.setVisibility(View.VISIBLE);
									tv_data_complete.setText("同步数据已完成！");
									tv_data_loading1.setText("已同步"+Blutooth_Until.blutooth_lists.size()+"条数据!");
									Blutooth_Until.blutooth_lists.clear();
                                    
								}
							});
							
						}

					} else if (select_Str.equals("DD")) { // 获取数据
						List<DataBean> lists = Blutooth_Until.godo(strData);
						Blutooth_Until.blutooth_lists.addAll(lists);
						for (int i = 0; i < lists.size(); i++) {
							Log.i("jsc", "Date:" + lists.get(i).getDate());
							Log.i("jsc", "PefValue:"
									+ lists.get(i).getPefValue());
							Log.i("jsc", "Pev1:" + lists.get(i).getPev1());
						}

						if (pack_iteration <= select_pack_number2) {
							String select_pack_send_number = String.format(
									"%02d", pack_iteration);
							Log.i("jsc", "select_pack_send_number_int:"
									+ select_pack_send_number);
							writeStringToGatt("5502" + select_pack_send_number
									+ "00"); // 55020000
							pack_iteration++;
						} else {
							// List<DataBean> list = new ArrayList<DataBean>();
							// DataBean db = new DataBean("日期","pef值","pev1值");
							// list.add(db);
							// NewQuestionaireActivity q = new
							// NewQuestionaireActivity();
							// q.saveData(list);
							// Blutooth_Until.blutooth_lists.clear();
							// Toast.makeText(Blutooth_Second.this, "命令删除",
							// 1).show();
							// NewQuestionaireActivity n = new
							// NewQuestionaireActivity();
							// n.saveData(Blutooth_Until.blutooth_lists);
							Log.i("jsc", "删除前！");
							
							Log.i("jsc", "Blutooth_Until.blutooth_lists:"+ Blutooth_Until.blutooth_lists.size());
							
							myHandler.post(new Runnable() {

								@Override
								public void run() {
									new NewQuestionaireActivity().saveData(Blutooth_Second.this,Blutooth_Until.blutooth_lists);
                                    
								}
							});
							

							
							Log.i("jsc", "命令删除");
							writeStringToGatt("5503");

							// writeStringToGatt("5503");
						}

					} else if (select_Str.equals("01")) {

						Log.i("jsc", "数据有错！！！");
					}

					// Toast.makeText(SecondActivity.this,"Read_收到的数据是 ： " +
					// sbValues, 1).show();
					// Log.i("jsc", "sbValues:" + sbValues);
					// tv_number2.setText(sbValues);
					// List<String> lists = Until.godo(strData);
					//
					// for (int i = 0; i < lists.size(); i++) {
					// Log.i("jsc", "lists:" + lists.get(i).toString());
					// }

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					Log.i("jsc", "报错");
				}
				// TODO Auto-generated method stub

			} else {

				Log.i("jsc", "----------------------------------");
			}

		}

		@Override
		public void onCharacteristicWrite(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic, int status) {
			// TODO Auto-generated method stub
			Log.i("jsc", "onCharacteristicWrite");
			super.onCharacteristicWrite(gatt, characteristic, status);
			gatt.readCharacteristic(readGattCharacteristic);
		}

		@Override
		public void onCharacteristicChanged(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic) {
			// TODO Auto-generated method stub
			super.onCharacteristicChanged(gatt, characteristic);
			data = characteristic.getValue();
			if (data != null && data.length > 0) {
				strData = getStringByBytes(data) + "\n";
				System.out.println("Changed_收到的数据是 ： " + strData);
				Log.i("jsc", "Changed_收到的数据是 ： " + strData);

				sbValues.insert(0, strData);
				myHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

					}
				});

			}
		}

		@Override
		public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
			// TODO Auto-generated method stub
			// 接收的信号强度指示
			super.onReadRemoteRssi(gatt, rssi, status);
		}

	};

	/**
	 * 把16进制String字符转变为byte[]
	 */
	public static byte[] getBytesByString(String data) {
		byte[] bytes = null;
		if (data != null) {
			data = data.toUpperCase();
			int length = data.length() / 2;
			char[] dataChars = data.toCharArray();
			bytes = new byte[length];
			for (int i = 0; i < length; i++) {
				int pos = i * 2;
				bytes[i] = (byte) (charToByte(dataChars[pos]) << 4 | charToByte(dataChars[pos + 1]));
			}
		}
		return bytes;
	}

	/**
	 * 取得在16进制字符串中各char所代表的16进制数
	 */
	private static byte charToByte(char c) {
		return (byte) "0123456789ABCDEF".indexOf(c);
	}

	/**
	 * byte[]转变为16进制String字符, 每个字节2位, 不足补0
	 */
	public static String getStringByBytes(byte[] bytes) {
		String result = null;
		String hex = null;
		if (bytes != null && bytes.length > 0) {
			final StringBuilder stringBuilder = new StringBuilder(bytes.length);
			for (byte byteChar : bytes) {
				hex = Integer.toHexString(byteChar & 0xFF);
				if (hex.length() == 1) {
					hex = '0' + hex;
				}
				stringBuilder.append(hex.toUpperCase());
			}
			result = stringBuilder.toString();
		}
		return result;
	}

}
